package org.testile.placeholderscript;

import java.util.Map;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import org.apache.commons.lang.Validate;

/**
 *
 * @author hvizmar
 */
public class BindingMapTransformer extends AbstractPatternTransformer {

	public BindingMapTransformer() {
		super(Pattern.compile("^([A-Z]+)\\[([a-zA-Z]+)\\]$"));
	}

	@Override
	protected String transformMatch(MatchResult match) {
		String mapId = match.group(1);
		String key   = match.group(2);

		return getValue(mapId, key);
	}

	private String getValue(String mapId, String key) {
		Map map = getMapFromBindings(mapId);

		if(!map.containsKey(key)) {
			throw new IllegalArgumentException("Map with id [" + mapId + "] does not contain the key [" + key + "]");
		}

		return String.valueOf(map.get(key));
	}

	private Map getMapFromBindings(String mapId) {
		Object o = engine.get(mapId);
		Validate.notNull(o, "No map in engine scope binding under id [" + mapId + "]");

		return getMap(o);
	}

	private Map getMap(Object o) {
		if(Map.class.isAssignableFrom(o.getClass())) {
			return Map.class.cast(o);
		}

		throw new IllegalStateException("Object not a map.");
	}
}
